// https://www.lintcode.com/problem/word-pattern/

public class Solution {
    /**
     * @param pattern: a string, denote pattern string
     * @param teststr: a string, denote matching string
     * @return: an boolean, denote whether the pattern string and the matching string match or not
     */
    public boolean wordPattern(String pattern, String teststr) {
        // write your code here
        HashMap<String, Character> t2p_map = new HashMap<>();
        HashMap<Character, String> p2t_map = new HashMap<>();
        String[] words = teststr.split(" ");
        for (int i = 0; i < pattern.length(); ++i) {
            Character c = pattern.charAt(i);
            String word = words[i];
            if ((!t2p_map.containsKey(word)) && (!p2t_map.containsKey(c))) {
                t2p_map.put(word, c);
                p2t_map.put(c, word);
            } else {
                if (t2p_map.containsKey(word)) {
                    if (t2p_map.get(word) != c) {
                        return false;
                    }
                }
                if (p2t_map.containsKey(c)) {
                    if (!p2t_map.get(c).equals(word)) {
                        return false;
                    }
                }
            }
        }
        return true;
    }
}